package com.qq.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.qq.bean.Users;
import com.qq.service.UsersService;
import com.qq.service.impl.UsersServiceImpl;

@MultipartConfig
@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		UsersService us = new UsersServiceImpl();
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		String repassword = request.getParameter("repassword");
		String realName = request.getParameter("realName");
		String nickName = request.getParameter("nickName");
		
		Part part = request.getPart("headImg");
		Date br = null;
		if (part == null || part.getSize()>1024*1024*10  || !part.getContentType().contains("image")) {
			request.setAttribute("headImgMsg", "请上传1mb以内的图片作为头像");
//			request.getRequestDispatcher("login.jsp").forward(request, response);
			return;
		}
		System.out.println(part);
		//文件名
		String fileName = part.getSubmittedFileName();
		//真实路径，存储路径
		String  realPath = "c:/qq/headImgs/"+fileName;
//		String savePath = 
		//访问路径
		String  visitPath = "/chatBlog/qq/headImgs/"+ fileName;
		
		part.write(realPath);
		Users user = new Users(realName,nickName,account,password,visitPath,0);
		int result = us.usersRegister(user);
		if(result == -1){
			File file = new File(realPath);
			if(file.exists()) {
				file.delete();
			}
			request.setAttribute("msg","用户名已经存在");
			request.getRequestDispatcher("login.jsp").forward(request,response);
		}else{
			response.sendRedirect("login.jsp");
		}
	}

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}